<template>
  <div class="addCard">
    <el-dialog v-model="dialogFormVisible" title="添加">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="公告标题" prop="noticeTitle">
          <el-input v-model="ruleForm.noticeTitle" />
        </el-form-item>
        <el-form-item label="公告描述" prop="noticeDescribe">
          <el-input
            v-model="ruleForm.noticeDescribe"
            autosize
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="公告图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageURL" :src="imageURL" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示层级" prop="top">
          <el-input-number v-model="ruleForm.noticeTop" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="back">返回</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">
            提交</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Ref, ref, watch, reactive } from "vue";
import { useRouter } from "vue-router";
import request from "../axios/index";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import type { UploadFile, UploadProps, FormInstance } from "element-plus";

interface AddNotice {
  noticeTitle: string;
  noticeDescribe: string;
  image: any;
  noticeTop: string;
}

export default {
  name: "AddCard",
  setup(props, { emit }) {
    //定义图片存储路径
    let imageURL: Ref<string> = ref("");
    const ruleFormRef = ref<FormInstance>();
    //定义表单内容
    let ruleForm: AddNotice = reactive({
      noticeTitle: "",
      noticeDescribe: "",
      image: "",
      noticeTop: "0",
    });
    //定义表单规则
    const rules = reactive<FormRules>({
      noticeTitle: [
        {
          required: true,
          message: "请输入标题",
          trigger: "blur",
        },
      ],
      noticeDescribe: [
        {
          required: true,
          message: "请输入内容描述",
          trigger: "blur",
        },
      ],
    });

    const router = useRouter();

    const dialogFormVisible = ref(true);
    //返回上一级
    function back() {
      router.back();
    }

    //选中图片
    const handleAvatarSuccess = (uploadFile: UploadFile) => {
      ruleForm.image = uploadFile.raw;
      imageURL.value = URL.createObjectURL(uploadFile.raw!);
    };
    //上传规则
    const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
      if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("请上传Jpeg/Jpg/Png格式图片");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error("图片大小请不要超过5MB!");
        return false;
      }
      return true;
    };

    //提交
    const submit = async (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          ElMessageBox.confirm("是否确认提交信息")
            .then(() => {
              let formData = new FormData();
              formData.append("noticeTitle", ruleForm.noticeTitle);
              formData.append("noticeDescribe", ruleForm.noticeDescribe);
              formData.append("image", ruleForm.image);
              formData.append("noticeTop", ruleForm.noticeTop);
              request
                .post("/admin/notice/addNotice", formData, {
                  headers: {
                    "Content-Type": "multipart/form-data",
                  },
                })
                .then((res) => {
                  if (res.data.code === 200) {
                    ElMessage({
                      message: res.data.message,
                      type: "success",
                    });
                    emit("reFresh", null);
                    back();
                  } else {
                    ElMessage({
                      message: res.data.message,
                      type: "error",
                    });
                    back();
                  }
                });
            })
            .catch((err) => {
              ElMessage("已取消添加");
            });
        }
      });
    };

    watch(
      () => dialogFormVisible.value,
      (newValue, oldValue) => {
        if (!newValue) {
          back();
        }
      }
    );

    return {
      dialogFormVisible,
      imageURL,
      ruleFormRef,
      ruleForm,
      rules,
      back,
      handleAvatarSuccess,
      beforeAvatarUpload,
      submit,
    };
  },
};
</script>

<style scoped>
.addCard {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  z-index: 9;
  background-color: #fff;
}
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.el-dialog__body {
  padding-top: -10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>